package main

import(
    "fmt"
    "os"
    "net/http"
    "io/ioutil"
    "encoding/json"
    "path/filepath"
)

const(
    RESOURCE = "http://local.com/API/File/getProjectFolders"
)

type folder struct {
    Code int `json:"code"`
    Msg  string `json:"msg"`
    Data struct {
        Project struct {
            Id string `json:"id"`
            Name string `json:"name"`
        } `json:"project"`
        Link []struct {
            Id string `json:"id"`
            Name string `json:"name"`
            Pid string `json:"pid"`
            Type string `json:"type"`
        } `json:"link"`
    } `json:"data"`
}

func main(){

    fmt.Println("请输入项目ID")
    var project_id string
    project_id = getProject()
    //params := os.Args
    //project_id := params[1]
    //project_id := "428"

    resp, getErr := http.Get(RESOURCE + "?project_id=" + project_id)
    if getErr != nil {
        echoError("http:获取项目层级结构失败")
    }
    defer resp.Body.Close()
    body, readErr := ioutil.ReadAll(resp.Body)
    if readErr != nil {
        echoError("readBody:获取项目层级结构失败")
    }
    //fmt.Println(string(body))
    f := folder{}
    jsonErr := json.Unmarshal(body,&f)
    if jsonErr != nil {
        echoError("格式化层级结构失败。")
    }
    if f.Code != 200 {
        echoError(f.Msg)
    }
    fmt.Println("正在生成”" + f.Data.Project.Name + "“层级结构...")
    path,_ := os.Executable()
    dir := filepath.Dir(path)

    //创建文件夹
    //创建项目层级文件夹
    createErr := os.Mkdir(dir + "/" + f.Data.Project.Name,os.ModePerm)
    if createErr != nil {
        echoError("创建目录：" + dir + "/" + f.Data.Project.Name + "失败。")
    }
    path = dir + "/" + f.Data.Project.Name
    create(f,path)
    echoError("创建完成。")
}

func create(f folder,path string){
    list := f.Data.Link
    temp := make(map[string]string)
    for i := 0 ; i < len(list); i++ {
        if list[i].Pid == "0" {
            os.MkdirAll(path + "/" + list[i].Name,os.ModePerm)
            temp[list[i].Id] = path + "/" + list[i].Name
        }else{
            if value,ok := temp[list[i].Pid]; ok {
                os.MkdirAll(value + "/" + list[i].Name,os.ModePerm)
                temp[list[i].Id] = value + "/" + list[i].Name
                if list[i].Type == "stages" && list[i].Name == "efx" {
                    os.Mkdir(temp[list[i].Id] + "/deepexr",os.ModePerm)
                }
            }
        }
    }
}

func echoError(msg string) {
    fmt.Println(msg + "\n按(Enter)键退出...")
    var str string
    fmt.Scanln(&str)
    os.Exit(0)
}

func getProject() (string) {
    var project_id string
    fmt.Scanln(&project_id)
    return project_id
}
